#include "widget.h"
#include "ui_widget.h"
#include <QUdpSocket>
#include <QHostInfo>
#include <QMessageBox>
#include <QScrollBar>
#include <QDateTime>
#include <QNetworkInterface>
#include <QProcess>
#include <QDataStream>
#include <QFileDialog>
#include "client.h"
#include "server.h"

Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{
    ui->setupUi(this);
  //  drawer =new Drawer;
    //drawer->show();
    srv = new Server(this);
    connect(srv,SIGNAL(sndFileName(QString)),this,SLOT(getFileName(QString)));
}

Widget::Widget(QWidget *parent,QString username):QWidget(parent),ui(new Ui::Widget)
{
    ui->setupUi(this);
    setFixedSize(730,450);

    uName = username;
    udpSocket = new QUdpSocket(this);

    port =65533;
    udpSocket->bind(port,QUdpSocket::ShareAddress|QUdpSocket::ReuseAddressHint);
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(processPendingDatagrams()));
    sndMsg(UsrEnter);
}


//发送广播消息函数
void Widget::sndMsg(MsgType type, QString srvaddr)
{
    QByteArray data;
    QDataStream out(&data,QIODevice::WriteOnly);
    QString  address = getIP();
    out << type << getUsr();

    switch(type)
    {
    case Msg:{
        if(ui->msgTextEdit->toPlainText()=="")
        {
            QMessageBox::warning(0,tr("警告"),tr("发送内容不能为空"),QMessageBox::Ok);
            return;
        }
        out << address << getMsg();
        ui->mesgBrowser->verticalScrollBar()->setValue(
                    ui->mesgBrowser->verticalScrollBar()->maximum());
        break;
    }
    case UsrEnter:
        out << address;
        break;

    case UsrLeft:

        break;
    case FileName:{
        int row = ui->usrTblWidget->currentRow();
        QString clntaddr = ui->usrTblWidget->item(row,1)->text();
        out << address << clntaddr<< fileName;
        break;
        }
    case Refuse:

        out << srvaddr;
        break;
    }

    udpSocket->writeDatagram(data,data.length(),QHostAddress::Broadcast,port);
}

//接收数据包消息
void Widget::processPendingDatagrams()
{
    while(udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());

        udpSocket->readDatagram(datagram.data(),datagram.size());
        QDataStream in(&datagram,QIODevice::ReadOnly);
        int msgType;
        in >> msgType;

        QString usrName,ipAddr,msg;

        QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

        switch(msgType)
        {
        case Msg:
            in >> usrName >> ipAddr>> msg;
            ui->mesgBrowser->setTextColor(Qt::blue);
            ui->mesgBrowser->setCurrentFont(QFont("Times New Roman",12));
            ui->mesgBrowser->append("[" +usrName+ "]" +time);
            ui->mesgBrowser->append(msg);
            break;
        case UsrEnter:
            in >> usrName >> ipAddr;
            userEnter(usrName,ipAddr);
            break;
        case UsrLeft:
            in >> usrName;
            userLeft(usrName,time);
            break;
        case FileName:
        {
           in >> usrName >>ipAddr;
           QString clnAddr,fileName;
           in >> clnAddr >> fileName;
           hasPendingFile(usrName,ipAddr,clnAddr,fileName);
            break;
        }
        case Refuse:
        {
            in >> usrName;
            QString srvAddr;
            in >> srvAddr;
            QString ipAddr = getIP();
            if(ipAddr == srvAddr)
            {
                srv->refused();
            }
        }   break;
        }
    }
}


//新用户上线
void Widget::userEnter(QString usrname, QString ipaddr)
{
    bool isEmpty = ui->usrTblWidget->findItems(usrname,Qt::MatchExactly).isEmpty();
    if(isEmpty)
    {
        QTableWidgetItem *usr = new QTableWidgetItem(usrname);
        QTableWidgetItem *ip =new QTableWidgetItem(ipaddr);
        ui->usrTblWidget->insertRow(0);
        ui->usrTblWidget->setItem(0,0,usr);
        ui->usrTblWidget->setItem(0,1,ip);
        ui->mesgBrowser->setTextColor(Qt::gray);
        ui->mesgBrowser->setCurrentFont(QFont("Times New Roman",12));
        ui->mesgBrowser->append(tr("%1 在线").arg(usrname));
        ui->usrNumLbl->setText(tr("%1 人").arg(ui->usrTblWidget->rowCount()));
        sndMsg(UsrEnter);
    }
}


//用户离开
void Widget::userLeft(QString usrname,QString time)
{
    int rowNum =ui->usrTblWidget->findItems(usrname,Qt::MatchExactly).first()->row();

    ui->usrTblWidget->removeRow(rowNum);
    ui->mesgBrowser->setTextColor(Qt::gray);
    ui->mesgBrowser->setCurrentFont(QFont("Times New Roman",10));
    ui->mesgBrowser->append(tr("%1 在 %2 离开").arg(usrname).arg(time));
    ui->usrNumLbl->setText(tr("%1 人").arg(ui->usrTblWidget->rowCount()));
}
//获取IP地址
QString Widget::getIP()
{
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach(QHostAddress addr,list)
    {
        if(addr.protocol() == QAbstractSocket::IPv4Protocol)
        {
            return  addr.toString();
        }
    }
    return 0;
}

//获取用户名
QString Widget::getUsr()
{
    return uName;
}


QString Widget::getMsg()
{
    QString msg = ui->msgTextEdit->toHtml();
    ui->msgTextEdit->clear();
    ui->msgTextEdit->setFocus();
    return msg;
}



Widget::~Widget()
{
    delete ui;
}

void Widget::on_sendBtn_clicked()
{
    sndMsg(Msg);
}


void Widget::getFileName(QString name)
{
    fileName = name;
    sndMsg(FileName);
}

void Widget::hasPendingFile(QString usrname, QString srvaddr, QString clntaddr, QString filename)
{
    QString ipAddr =getIP();
    if(ipAddr == clntaddr)
    {
        int btn = QMessageBox::information(this,tr("接收文件"),tr("来自%1(%2)的文件: %3,是否接收?").arg(usrname)
                                            .arg(srvaddr).arg(filename));

        if(btn==QMessageBox::Yes)
        {
            QString name = QFileDialog::getSaveFileName();

            if(!name.isEmpty())
            {
                Client *clnt = new Client;
                clnt->setFileName(name);
                clnt->setHostAddr(QHostAddress(srvaddr));
                clnt->show();
            }

        }
        else
        {
            sndMsg(Refuse,srvaddr);
        }
    }
}

void Widget::on_sendTBtn_clicked()
{

    if(ui->usrTblWidget->selectedItems().isEmpty())
    {
        QMessageBox::warning(0,tr("选择用户"),tr("请选择用户!"),QMessageBox::Ok);
        return;
    }
    srv->show();
    srv->initSrv();
}
